package net.xdclass.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.CouponCategoryEnum;
import net.xdclass.enums.CouponPublishEnum;
import net.xdclass.enums.CouponStateEnum;
import net.xdclass.exception.BizException;
import net.xdclass.interceptor.LoginInterceptor;
import net.xdclass.model.LoginUser;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.JsonData;
import net.xdclass.mapper.CouponMapper;
import net.xdclass.mapper.CouponRecordMapper;
import net.xdclass.model.CouponDO;
import net.xdclass.model.CouponRecordDO;
import net.xdclass.model.NewUserCouponRequest;
import net.xdclass.service.CouponService;
import net.xdclass.vo.CouponVO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CouponServiceImpl implements CouponService {

    /**
     *
     */
    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private CouponRecordMapper couponRecordMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public Map<String, Object> pageCouponActivity(int page, int size) {

        Page<CouponDO> pageInfo = new Page<>(page,size);

        IPage<CouponDO> couponDOPage = couponMapper.selectPage(pageInfo, new QueryWrapper<CouponDO>()
                .eq("publish", CouponPublishEnum.PUBLISH)
                .eq("category",CouponCategoryEnum.PROMOTION)
                .orderByDesc("create_time"));

        Map<String,Object> pageMap = new HashMap<>();
        pageMap.put("total_record",couponDOPage.getTotal());
        pageMap.put("total_page",couponDOPage.getPages());
        pageMap.put("current_data", couponDOPage.getRecords().stream().map(obj -> beanProcess(obj)).collect(Collectors.toList()));

        return pageMap;
    }

    /**
     * 领券接口
     * 获取优惠券是否存在
     * 校验优惠券是否可领：时间、库存、超过限制
     * 扣减库存
     * 保持领券记录
     *
     * @param couponId
     * @param categoryEnum
     * @return
     */
    //异常时会回滚数据
    @Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRED)
    @Override
    public JsonData addCoupon(long couponId, CouponCategoryEnum categoryEnum) {


        /**
         * 原生分布式锁 开始
         * 1、原子加锁 设置过期时间，防止宕机死锁
         * 2、原子解锁：需要判断是不是自己的锁
         */
        String lockKey = "lock:coupon:"+couponId;
        RLock lock = redissonClient.getLock(lockKey);
        //有watch dog默认30s，自动续期
        lock.lock();

        //尝试加锁，最多等待100秒，上锁以后10秒自动解锁
        //lock.tryLock(100, 10, TimeUnit.SECONDS);
        log.info("领券接口加锁成功：{}",Thread.currentThread().getId());
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        try {
            CouponDO couponDO = couponMapper.selectOne(new QueryWrapper<CouponDO>()
                    .eq("id", couponId)
                    .eq("category", categoryEnum.name())
                    .eq("publish", CouponPublishEnum.PUBLISH.name()));

            //优惠券是否可以领取
            this.couponCheck(couponDO, loginUser.getId());
            //构建领券记录
            CouponRecordDO couponRecordDO = new CouponRecordDO();
            BeanUtils.copyProperties(couponDO, couponRecordDO);
            couponRecordDO.setCreateTime(new Date());
            couponRecordDO.setUseState(CouponStateEnum.NEW.name());
            couponRecordDO.setUserId(loginUser.getId());
            couponRecordDO.setUserName(loginUser.getName());
            couponRecordDO.setCouponId(couponId);
            couponRecordDO.setId(null);

            //高并发下扣减劵库存，采用乐观锁,当前stock做版本号,延伸多种防止超卖的问题,一次只能领取1张，TODO
            int rows = couponMapper.reduceStock(couponId, couponDO.getStock());

            if (rows == 1) {
                //库存扣减成功才保存
                couponRecordMapper.insert(couponRecordDO);
            } else {
                log.warn("发放优惠券失败:{},用户:{}", couponDO, loginUser);
                throw new BizException(BizCodeEnum.COUPON_NO_STOCK);
            }
        }finally {
            lock.unlock();
            log.info("解锁成功");
        }
        return JsonData.buildSuccess();
    }

    /**
     * 用户微服务调用时候，没传递token
     * 本地直接调用发放优惠券发放，需要构造一个登录用户存贮在threadLocal
     * @param newUserCouponRequest
     * @return
     */
    @Transactional(rollbackFor=Exception.class,propagation= Propagation.REQUIRED)
    @Override
    public JsonData initNewUserCoupon(NewUserCouponRequest newUserCouponRequest) {

        LoginUser loginUser = new LoginUser();
        loginUser.setId(newUserCouponRequest.getUserId());
        loginUser.setName(newUserCouponRequest.getName());
        LoginInterceptor.threadLocal.set(loginUser);
        //查询新用户有哪些优惠券
        List<CouponDO> couponDOList = couponMapper.selectList(new QueryWrapper<CouponDO>()
                .eq("category", CouponCategoryEnum.NEW_USER.name()));

        for (CouponDO couponDO : couponDOList){
            //幂等操作，需要加锁
            this.addCoupon(couponDO.getId(),CouponCategoryEnum.NEW_USER);
        }

        return JsonData.buildSuccess();
    }

    private CouponVO beanProcess(CouponDO couponDO) {
        CouponVO couponVO = new CouponVO();
        BeanUtils.copyProperties(couponDO,couponVO);
        return couponVO;
    }

    /**
     * 优惠券检查
     * @param couponDO
     * @param userId
     */
    private void couponCheck(CouponDO couponDO,long userId){

        //优惠券不存在
        if(couponDO == null){
            throw  new BizException(BizCodeEnum.COUPON_NO_EXITS);
        }
        //库存不足
        if(couponDO.getStock()<=0){
            throw  new BizException(BizCodeEnum.COUPON_NO_STOCK);
        }
        //是否在领取时间范围
        long time = CommonUtil.getCurrentTimestamp();
        long start = couponDO.getStartTime().getTime();
        long end = couponDO.getEndTime().getTime();
        if(time < start || time > end){
            throw  new BizException(BizCodeEnum.COUPON_OUT_OF_TIME);
        }
        //用户是否超过限制
        int recordNum = couponRecordMapper.selectCount(new QueryWrapper<CouponRecordDO>()
                .eq("coupon_id",couponDO.getId())
                .eq("user_id",userId));

        if(recordNum>=couponDO.getUserLimit()){
            throw  new BizException(BizCodeEnum.COUPON_OUT_OF_LIMIT);
        }
    }
}
